###############################################################################################
# Author: Ranjith Antony <rptony At Gmail>
# URL: http://sunran.com
#
# This program is an interface to a flickr album. Program fetches the latest 75 pictures from 
# your flickr account. 
#
################################################################################################
import os
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from xml.dom import minidom

class AlbumMainPage(webapp.RequestHandler):
	
	#member variables, 
	#please visit flickr website inorder to get an api key
	m_szApiKey  = "place-your-key-here"
	#nsid is the userid, please clik on the rss link on your photstream 
	m_szNsid    = "user-id"	
	m_szRestEnd = "http://api.flickr.com/services/rest/?"
	m_pictDict = {} #Stores the urls of small and large files
	
	#Function creates a url based on methodname and params passed to it
	def constructUrl(self, methodname, params={}):
		url = self.m_szRestEnd+"api_key="+self.m_szApiKey+"&user_id="+self.m_szNsid+"&method="+methodname
		if len(params) != 0:
			for key, value in params.iteritems():
				url = url+"&"+str(key)+"="+str(value)
		return url
	
	#This function fetches the urls of an square image from the id of the image	
	def fetchThumbNails(self, id):
		sqr_source = ""
		med_source = ""
		url = self.constructUrl("flickr.photos.getSizes", {"photo_id":id})
		result = urlfetch.fetch(url)
		if result.status_code == 200:
			dom = minidom.parseString(result.content)
			sizes = dom.getElementsByTagName("size")
			for size in sizes:
				if size.hasAttributes():
					label = size.attributes["label"]
					if(str(label.value) == "Square"):
						sqr_source = size.attributes["source"]
					if(str(label.value) == "Medium"):
						med_source = size.attributes["source"]
						self.m_pictDict[str(sqr_source.value)] = str(med_source.value)
			dom.unlink()
    
    # A much easier way of constructing the url, avoids feature fetches
	def createUrlToPictures(self, pictType, farmId, serverId, photoId, secret):
		result = "http://farm%(farm_id)s.static.flickr.com/%(server_id)s/%(photo_id)s_%(secret_id)s_%(pict_type)s.jpg" %\
		         {'farm_id': farmId, 'server_id': serverId, 'photo_id': photoId, 'secret_id': secret, 'pict_type': pictType }
		return result
		
	#default function called by google appengine when a GET method is encountered
	def get(self):
		url = self.constructUrl("flickr.people.getPublicPhotos", {"per_page":75})
		result = urlfetch.fetch(url)
		if result.status_code == 200:
			#self.response.headers['Content-Type'] = 'text/plain'
			dom = minidom.parseString(result.content)
			photos = dom.getElementsByTagName("photo")
			for photo in photos:
				if photo.hasAttributes():
					photo_id = photo.attributes["id"]
					farm_id  = photo.attributes["farm"]
					server_id= photo.attributes["server"]
					secret_id= photo.attributes["secret"]
					sqr_url = self.createUrlToPictures('s', farm_id.value, server_id.value, photo_id.value, secret_id.value)
					med_url = self.createUrlToPictures('b', farm_id.value, server_id.value, photo_id.value, secret_id.value)
					self.m_pictDict[sqr_url] = str(med_url)
					#self.fetchThumbNails(photo_id.value)
			dom.unlink()

			template_values = {
			'thumbs': self.m_pictDict,
			}

			path = os.path.join(os.path.dirname(__file__), 'index.html')
			self.response.out.write(template.render(path, template_values))

					 
					
					 
			

application = webapp.WSGIApplication([('/', AlbumMainPage)], debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()			
			
	
			
		